﻿function AccountViewModel(model) {
    var selfModel = this;

    Main.Page.Init("Start", "Account");

    selfModel.Login = ko.observable(new LoginViewModel(model.Login));
    selfModel.Register = ko.observable(new RegisterViewModel(model.Register));

    selfModel.AttemptLogin = function () {
        if (Main.Validation.ModelIsValid(selfModel.Login())) {
            ui.Animation.ShowLoading();

            var method = whoever.AJAX.Method({
                data: ko.toJSON(selfModel.Login),
                formId: "login"
            });

            method.success(function (result) {
                if (!result.Success) {
                    selfModel.Login().FailedSubmit(true);
                    ui.Animation.HideLoading(function () { ui.Message.Warning(result.Message); });
                } else if (result.MustRedirect)
                    window.location.href = result.RedirectURL;
            });
        } else {
            selfModel.Login().FailedSubmit(true);
            ui.Message.Warning(formErrorMessage);
        }
    };

    selfModel.AttemptSignup = function () {
        if (Main.Validation.ModelIsValid(selfModel.Register())) {
            ui.Animation.ShowLoading();

            var method = whoever.AJAX.Method({
                data: ko.toJSON(selfModel.Register),
                formId: "signup"
            });

            method.success(function (result) {
                if (!result.Success) {
                    selfModel.Register().FailedSubmit(true);
                    ui.Animation.HideLoading(function () { ui.Message.Warning(result.Message); });
                } else if (result.MustRedirect)
                    window.location.href = result.RedirectURL;
            });
        } else {
            selfModel.Register().FailedSubmit(true);
            ui.Message.Warning(formErrorMessage);
        }
    };
}